package com.cheer.ba.view.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.ConstantTag;
import com.cheer.ba.constant.H5Address;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.constant.IntentKey;
import com.cheer.ba.event.BaseEvent;
import com.cheer.ba.model.OilCardInfoModel;
import com.cheer.ba.model.OilMealModel;
import com.cheer.ba.presenter.impl.OilMealPresenter;
import com.cheer.ba.utils.CountDownTimer;
import com.cheer.ba.utils.Currency;
import com.cheer.ba.utils.DensityUtils;
import com.cheer.ba.utils.ShareNewsUtil;
import com.cheer.ba.utils.StringUtils;
import com.cheer.ba.view.base.BaseCommAty;
import com.cheer.ba.view.base.CommonAdapter;
import com.cheer.ba.view.base.ViewHolder;
import com.cheer.ba.widget.MyGridView;
import com.umeng.socialize.UMShareAPI;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 柴油套餐
 *
 * @author HQ
 *         created at 2017/5/9 0009 16:57
 */
public class OilSetMealAty extends BaseCommAty implements AdapterView.OnItemClickListener {

    //充值金额套餐
    @BindView(R.id.id_meal_gridV)
    MyGridView myGridView;
    private CommonAdapter<OilMealModel> mAdapter;
    private List<OilMealModel> mMeals = new ArrayList<OilMealModel>();

    //企业进入
    @BindView(R.id.id_meal_qye_linear)
    LinearLayout mQyeLinear;
    //减
    @BindView(R.id.id_mail_desc_txt)
    TextView mTxtDesc;
    //加
    @BindView(R.id.id_meal_add_txt)
    TextView mTxtAdd;
    // 输入框
    @BindView(R.id.id_meal_num_edit)
    EditText mEditOil;

    //折扣
    @BindView(R.id.id_oil_discount_txt)
    TextView mTxtOilDiscount;

    //有油卡
    @BindView(R.id.id_my_default_card_rela)
    RelativeLayout mRelaHadOilCard;
    //是否默认卡
    @BindView(R.id.id_is_default_txt)
    TextView mTxtDefaultImg;
    //卡是否激活
    @BindView(R.id.id_activity_txt)
    TextView mTxtCardActivity;
    //油卡ｌｏｇｏ
    @BindView(R.id.id_oil_logo_img)
    ImageView mImgOilLogo;
    //油卡所属机构
    @BindView(R.id.id_oil_name_txt)
    TextView mTxtOilName;
    //油卡类别
    @BindView(R.id.id_oil_card_txt)
    TextView mTxtOilType;
    //油卡卡号
    @BindView(R.id.id_oil_card_num_txt)
    TextView mTxtOilCardNum;
    private String mSaveCardNum;

    //无油卡
    @BindView(R.id.id_no_oil_card_linear)
    LinearLayout mLinearNoOilCard;

    //记录充值额度
    private String mSaveMoney;

    //记录支付原价
    private String mOrinialPrice;

    //记录套餐id
    private String mProductId;

    //记录油卡id
    private String mOilCardId;

    //实际付款金额
    @BindView(R.id.id_recharge_money_txt)
    TextView mTxtActualPrice;

    private ShareNewsUtil mShare;

    //记录油卡的信息
    private OilCardInfoModel mSaveOilCardInfo;

    //是否从当前页面点击进入的详情
    private boolean isJump = false;


    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_oil_set_meal, null, false));
    }

    @Override
    public void initPresenter() {
        presenter = new OilMealPresenter();
    }

    @Override
    public boolean hasDataInPage() {
        return !mMeals.isEmpty();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.recharge_meal));
        setTitleIcon(R.drawable.ic_sharer, false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mShare.showShare();
            }
        });
        mTxtOilDiscount.setText("无");
        mTxtActualPrice.setText("0元");
        mShare = new ShareNewsUtil(aty, "为了省钱的名义！", "加油省钱？选加油啦错不了！", H5Address.REMIND_RECHARGE, "");
        EventBus.getDefault().register(this);
        mEditOil.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSaveMoney = s + "";
                computePayMoney(StringUtils.toInt(mSaveMoney, 0));
            }

            @Override
            public void afterTextChanged(Editable s) {
                String text = s.toString();
                int len = text.length();
                if (len == 1 && text.equals("0")) {
                    s.clear();
                }
            }
        });
    }

    @Override
    public void initData() {
        if (TextUtils.equals("3", Session.getUserOrgType())) {
            mQyeLinear.setVisibility(View.VISIBLE);
            myGridView.setVisibility(View.GONE);
            mEditOil.setText("500");
            computePayMoney(500);
            mTxtDesc.setSelected(true);
            mTxtAdd.setSelected(true);

            if (Session.getUserIsLogin()) {
                ((OilMealPresenter) presenter).getMyOilCards(false, "0", "", "", "", "", "");
            } else {
                mRelaHadOilCard.setVisibility(View.GONE);
                mLinearNoOilCard.setVisibility(View.VISIBLE);
            }
        } else {
            mQyeLinear.setVisibility(View.GONE);
            myGridView.setVisibility(View.VISIBLE);
            final int width = DensityUtils.getScreenW(aty) / 3;
            LinearLayout.LayoutParams grid = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, width * 2);
//        grid.setMargins(DensityUtils.px2dip(aty, 30), 0, DensityUtils.px2dip(aty, 30), 0);
            myGridView.setLayoutParams(grid);
            myGridView.setColumnWidth(width);
            mAdapter = new CommonAdapter<OilMealModel>(aty, mMeals, R.layout.adp_oil_meal) {
                @Override
                public void convert(ViewHolder helper, OilMealModel item) {
                    LinearLayout mLinear = (LinearLayout) helper.getViewById(R.id.id_click_linear);
                    TextView mTxtCost = (TextView) helper.getViewById(R.id.id_discost_txt);
                    TextView mTxtPay = (TextView) helper.getViewById(R.id.id_desc_txt);
                    mTxtPay.setVisibility(View.GONE);
                    if (checkMap.get(helper.getPosition(), false)) {
                        mLinear.setSelected(true);
                        mTxtCost.setSelected(true);
                        mTxtPay.setSelected(true);
                    } else {
                        mLinear.setSelected(false);
                        mTxtCost.setSelected(false);
                        mTxtPay.setSelected(false);
                    }
                    mTxtCost.setText(Currency.returnDollar(item.getMoney()));
                    if (!TextUtils.equals("3", Session.getUserOrgType())) {
                        mTxtPay.setVisibility(View.VISIBLE);
                        mTxtPay.setText("折后：" + Currency.returnDollar(item.getMoney(), item.getDiscount()) + "元");
                    }
                    if (TextUtils.equals("0", item.getPackageStatus())) {
                        mTxtCost.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                        mTxtPay.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    }
                }
            };
            myGridView.setAdapter(mAdapter);
            myGridView.setOnItemClickListener(this);
            //获得加油套餐
            ((OilMealPresenter) presenter).getOilCards();
        }
    }

    /**
     * 处理买油的量
     *
     * @param flag 0  减 1加
     */
    public void handOilNum(String msg, int flag) {
        int i;
        if (StringUtils.isEmpty(msg)) {
            i = 0;
        } else {
            i = Integer.parseInt(msg);
            if (flag == 0) {
                mTxtAdd.setSelected(true);
                i -= 100;
                if (i <= 0) {
                    i = 0;
                    mTxtDesc.setSelected(false);
                } else {
                    mTxtDesc.setSelected(true);
                }
            } else {
                mTxtDesc.setSelected(true);
                i += 100;
                if (i >= 5000) {
                    i = 5000;
                    mTxtAdd.setSelected(false);
                } else {
                    mTxtAdd.setSelected(true);
                }
            }
        }
        mEditOil.setText(i + "");
        computePayMoney(i);
    }

    @OnClick({R.id.id_mail_desc_txt, R.id.id_meal_add_txt, R.id.id_look_rule_rela, R.id.id_remind_recharge_txt, R.id.id_choose_my_oil_txt, R.id.id_my_default_card_rela, R.id.id_no_oil_card_linear, R.id.id_quick_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_mail_desc_txt:
                // 减
                handOilNum(mSaveMoney, 0);
                break;
            case R.id.id_meal_add_txt:
                // 加
                handOilNum(mSaveMoney, 1);
                break;
            //充值返利说明
            case R.id.id_remind_recharge_txt:
                CommH5WithTitleAty.startCommonH5(aty, H5Address.REMIND_RECHARGE, "活动说明", false, false, "", "", "");
                break;
            //充值返利说明
            case R.id.id_look_rule_rela:
                CommH5WithTitleAty.startCommonH5(aty, H5Address.REMIND_RECHARGE, "活动说明", false, false, "", "", "");
                break;
            //选择加油卡,进入我的油卡列表
            case R.id.id_choose_my_oil_txt:
                if (isLogin(true)) {
                    isJump = false;
                    Intent card = new Intent(aty, OilCardAty.class);
                    card.putExtra(IntentKey.General.KEY_PAGE, true);
                    showActivity(aty, card);
                }
                break;
            //进入油卡详情
            case R.id.id_my_default_card_rela:
                if (null == mSaveOilCardInfo) {
                    return;
                }
                isJump = true;
                Intent intent = new Intent(aty, OilCardDetailAty.class);
                intent.putExtra(IntentKey.General.KEY_MODEL, mSaveOilCardInfo);
                showActivity(aty, intent);
                break;
            //添加油卡
            case R.id.id_no_oil_card_linear:
                if (isLogin(true)) {
                    showActivity(aty, AddOilCardAty.class);
                }
                break;
            //立即充值
            case R.id.id_quick_btn:
                if (isLogin(true)) {
                    if (CountDownTimer.isFastClick(2000)) {
                        return;
                    }
                    if (mRelaHadOilCard.getVisibility() == View.VISIBLE) {
                        if (StringUtils.isEmpty(mSaveMoney)) {
                            SVProgressHUD.showInfoWithStatus(aty, "请选择充值金额");
                        } else {
                            isJump = true;
                            TransitAty.start3TransitAty(aty, IntentCode.General.JUMP_RECHARGE, mProductId, mOilCardId, mOrinialPrice, mSaveMoney, "0", mSaveCardNum);
                        }
                    } else {
                        SVProgressHUD.showInfoWithStatus(aty, "请选择要充值的油卡");
                    }
                }
                break;
        }
    }

    /**
     * 计算需要支付的金额
     */
    public void computePayMoney(int position) {
        if (TextUtils.equals("3", Session.getUserOrgType())) {
            mOrinialPrice = Currency.return2Point(position + "");
            mSaveMoney = position + "";
            mTxtActualPrice.setText(mSaveMoney + "元");
            mProductId = "";
        } else {
            OilMealModel model = (OilMealModel) mAdapter.getItem(position);
            if (Double.parseDouble(model.getDiscount()) - 1 != 0) {
                mTxtOilDiscount.setText(StringUtils.removePoint(Double.parseDouble(model.getDiscount()) * 100 + "") + "折");
            } else {
                mTxtOilDiscount.setText("无折扣");
            }

            mOrinialPrice = model.getMoney();
            if (TextUtils.equals("3", Session.getUserOrgType())) {
                mSaveMoney = Currency.returnDollar(model.getMoney()).replace("元", "");
                mTxtActualPrice.setText(mSaveMoney + "元");
            } else {
                mSaveMoney = Currency.returnDollar(model.getMoney(), model.getDiscount());
                mTxtActualPrice.setText(mSaveMoney + "元");
            }

            mProductId = model.getUid();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        OilMealModel model = (OilMealModel) mAdapter.getItem(position);
        if (TextUtils.equals("0", model.getPackageStatus())) {
            SVProgressHUD.showInfoWithStatus(aty, "该充值金额已失效，请选择其他充值金额");
            return;
        }
        mAdapter.setCheckAtPosFalse(position, true);
        computePayMoney(position);
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(ConstantTag.GET_OIL_CARDS, tag)) {
                //柴油卡充值套餐
                List<OilMealModel> meals = (List<OilMealModel>) t;
                mMeals.clear();
                mMeals.addAll(meals);
                mAdapter.notifyDataSetChanged();
                mAdapter.setCheckAtPosFalse(0, true);
                computePayMoney(0);
                if (Session.getUserIsLogin()) {
                    ((OilMealPresenter) presenter).getMyOilCards(false, "0", "", "", "", "", "");
                } else {
                    mRelaHadOilCard.setVisibility(View.GONE);
                    mLinearNoOilCard.setVisibility(View.VISIBLE);
                }
            } else if (TextUtils.equals(ConstantTag.MY_OIL_CARDS, tag)) {
                //我的油卡
                List<OilCardInfoModel> oilCards = (List<OilCardInfoModel>) t;
                mSaveOilCardInfo = oilCards.get(0);
                mRelaHadOilCard.setVisibility(View.VISIBLE);
                mLinearNoOilCard.setVisibility(View.GONE);
                mTxtOilCardNum.setText(StringUtils.replaceBankString(mSaveOilCardInfo.getCardNum(), 0));
                mSaveCardNum = mSaveOilCardInfo.getCardNum();
                mOilCardId = mSaveOilCardInfo.getUid();
                if (mSaveOilCardInfo.getCardStatus() == 1) {
                    //申请中
                    mTxtCardActivity.setText("未激活");
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.red));
                } else {
                    //激活
                    mTxtCardActivity.setText("余额：" + Currency.returnDollar(mSaveOilCardInfo.getBalance()));
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.white));
                }
                mTxtOilType.setText("加油啦车队卡");
                if (mSaveOilCardInfo.getCardType() == 1) {
                    mTxtOilName.setText("中国石油（" + mSaveOilCardInfo.getProvince() + "）");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_china_oil_logo);
                } else if (mSaveOilCardInfo.getCardType() == 2) {
                    mTxtOilName.setText("中国石化（" + mSaveOilCardInfo.getProvince() + "）");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_shihua_logo);
                } else {
                    mTxtOilName.setText("中国海油（" + mSaveOilCardInfo.getProvince() + "）");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_haiyou_logo);
                }
            } else if (TextUtils.equals(ConstantTag.DATA_ERROR, tag)) {
                mSaveOilCardInfo = null;
                mRelaHadOilCard.setVisibility(View.GONE);
                mLinearNoOilCard.setVisibility(View.VISIBLE);
            } else if (TextUtils.equals(ConstantTag.DATA_SUCCESS_NULL, tag)) {
                mSaveOilCardInfo = null;
                mRelaHadOilCard.setVisibility(View.GONE);
                mLinearNoOilCard.setVisibility(View.VISIBLE);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventUpdate(BaseEvent event) {
        //返回类型
        String type = event.type;
        if (TextUtils.equals(type, IntentKey.Oil.KEY_OIL_MODEL)) {
            //添加油卡成功或者选择油卡成功
            OilCardInfoModel oilMeal = (OilCardInfoModel) event.model;
            if (null != oilMeal) {
                mSaveOilCardInfo = oilMeal;
                mRelaHadOilCard.setVisibility(View.VISIBLE);
                mLinearNoOilCard.setVisibility(View.GONE);
                mTxtOilCardNum.setText(StringUtils.replaceBankString(oilMeal.getCardNum(), 0));
                mSaveCardNum = oilMeal.getCardNum();
                mOilCardId = oilMeal.getUid();
                if (oilMeal.getCardStatus() == 1) {
                    //申请中
                    mTxtCardActivity.setBackgroundResource(R.color.transparent);
                    mTxtCardActivity.setText("未激活");
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.red));
                } else {
                    //激活
                    mTxtCardActivity.setBackgroundResource(R.color.transparent);
                    mTxtCardActivity.setText("余额：" + Currency.returnDollar(oilMeal.getBalance()));
                    mTxtCardActivity.setTextColor(getResources().getColor(R.color.white));
                }
                mTxtOilType.setText("加油啦车队卡");
                if (oilMeal.getCardType() == 1) {
                    mTxtOilName.setText("中国石油");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_china_oil_logo);
                } else if (oilMeal.getCardType() == 2) {
                    mTxtOilName.setText("中国石化");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_shihua_logo);
                } else {
                    mTxtOilName.setText("中国海油");
                    mImgOilLogo.setBackgroundResource(R.drawable.ic_haiyou_logo);
                }
            }
        } else if (TextUtils.equals(type, IntentKey.Login.KEY_LOGIN_SUCCESS)) {
            SVProgressHUDDismiss();
            //登录成功
            ((OilMealPresenter) presenter).getMyOilCards(false, "0", "", "", "", "", "");
        } else if (TextUtils.equals(type, IntentKey.Oil.DEL_OIL_CARD)) {
            //移除油卡成功
            String id = event.id;
            if (TextUtils.equals(id, mOilCardId)) {
                ((OilMealPresenter) presenter).getMyOilCards(false, "0", "", "", "", "", "");
            }
        } else if (TextUtils.equals(type, IntentKey.Oil.OIL_ACTIVITY_SUCCESS)) {
            //激活油卡成功
            String id = event.id;
            String money = mSaveOilCardInfo.getBalance();
            if (TextUtils.equals(id, mOilCardId)) {
                mTxtCardActivity.setBackgroundResource(R.color.transparent);
                mTxtCardActivity.setText("余额：" + Currency.returnDollar(money));
                mTxtCardActivity.setTextColor(getResources().getColor(R.color.white));
                mSaveOilCardInfo.setCardStatus(2);
            }
        } else if (TextUtils.equals(type, ConstantTag.BIND_DRIVERS)) {
            //绑定司机成功
            OilCardInfoModel model = (OilCardInfoModel) event.model;
            mSaveOilCardInfo.setPlateNumber(model.getPlateNumber());
            mSaveOilCardInfo.setCustName(model.getCustName());
            mSaveOilCardInfo.setCardTel(model.getCardTel());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /** attention to this below ,must add this**/
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
